package com.chookss.mine.personal;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.StaticClass;
import com.chookss.mine.adapter.MyMoreVideoAdapter;
import com.chookss.mine.adapter.MyVideoAdapter;
import com.chookss.mine.adapter.MyVideoListAdapter;
import com.chookss.mine.entity.MyViedeoEntity;
import com.chookss.tools.GridSpacingItemDecoration;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.video.entity.VideoEntity;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;
//更多小视频
public class MyMoreVediosActivity extends BaseAct {


    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.rvView)
    RecyclerView recyclerView;
    @BindView(R.id.srlView)
    SmartRefreshLayout smrRf;
    @BindView(R.id.ivNone)
    ImageView ivNone;
    @BindView(R.id.tvNone)
    TextView tvNone;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    @BindView(R.id.llBg)
    LinearLayout llBg;
    private String employeeCode;
    private String videoCollectionsCode="",videoCollectionsName="";
    private MyMoreVideoAdapter adapter;
    private int currentPage = 1;
    private boolean isEnd = false;//是否到底
    private List<VideoEntity> list = new ArrayList<>();
    private int type = 0;//0自己的主页1别人的主页

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        setContentView(R.layout.common_srlview_center);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        employeeCode = getIntent().getStringExtra("employeeCode");
        videoCollectionsCode = getIntent().getStringExtra("videoCollectionsCode");
        videoCollectionsName = getIntent().getStringExtra("videoCollectionsName");
        commonTitleTxt.setText(videoCollectionsName);
        ivNone.setBackgroundResource(R.drawable.icon_default_no_video);
        tvNone.setText("集合下暂无数据");
        smrRf.setPadding(0, Utils.dip2px(this, 12), 0, 0);
        GridLayoutManager gridLayoutManager1 = new GridLayoutManager(this, 3);
        recyclerView.setLayoutManager(gridLayoutManager1);
        GridSpacingItemDecoration gridSpacingItemDecoration = new GridSpacingItemDecoration(3, Utils.dip2px(this, 6), false);
        recyclerView.addItemDecoration(gridSpacingItemDecoration);
        adapter = new MyMoreVideoAdapter(R.layout.item_my_video, this, list, "1", type);
        recyclerView.setAdapter(adapter);
        ((SimpleItemAnimator)recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        smrRf.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getData();
                }
            }
        });
        smrRf.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                currentPage = 1;
                isEnd = false;
                getData();
            }
        });
        smrRf.autoRefresh();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        currentPage = 1;
        isEnd = false;
        getData();
    }

    private void getData() {
        Map<String, String> allmap = new HashMap<>();
        allmap.put("videoCollectionsCode", videoCollectionsCode);
        allmap.put("employeeCode", employeeCode);
        allmap.put("pageNum", currentPage + "");
        allmap.put("pageSize", "20");
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<List<VideoEntity>>>() {
        }.getType(), null, Urls.selectMyVideoByCollectionsCode, SignUtils2.makeSignStr(allmap), false, new ObserverCallback<List<VideoEntity>>() {
            @Override
            public void onSuccess(List<VideoEntity> data) {
                if (currentPage == 1) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                }
                if(smrRf==null||llNone==null){
                    return;
                }
                int oldIndex=list.size();
                if (data != null && data.size() > 0) {
                    list.addAll(data);
                    adapter.notifyItemRangeChanged(oldIndex,data.size());
                    smrRf.setVisibility(View.VISIBLE);
                    llNone.setVisibility(View.GONE);
                } else {
                    isEnd = true;
                    if (list.size() == 0) {
                        smrRf.setVisibility(View.GONE);
                        llNone.setVisibility(View.VISIBLE);
                    }

                }
                loadEnd();
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    @OnClick({R.id.common_title_back})
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
        }

    }

    private void loadEnd() {
        if (null != smrRf && smrRf.getState() == RefreshState.Refreshing)
            smrRf.finishRefresh(true);
        if (null != smrRf && smrRf.getState() == RefreshState.Loading)
            smrRf.finishLoadMore(true);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            Map<String, String> map = messageEvent.getHashMap();
            if (map.containsKey("videoId")) {
                refreshVedio(map);
            } else if (map.containsKey("deleteVideoIdId")) {
                deleteVideo(map.get("deleteVideoIdId"));
            }
        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if ("RefreshVideo".equals(msg)) {
                currentPage = 1;
                isEnd = false;
                getData();
            }
        }
    }
    private void deleteVideo(String vedioId) {
        if(smrRf==null||llNone==null){
            return;
        }
        for (int i = 0; i < list.size(); i++) {
            VideoEntity videoListBean = list.get(i);
            if (videoListBean.videoId.equals(vedioId)) {
                list.remove(i);
                adapter.notifyItemRemoved(i);
                adapter.notifyItemRangeChanged(i, list.size() - i);
                if (list.size() == 0) {
                    smrRf.setVisibility(View.GONE);
                    llNone.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    private void refreshVedio(Map<String, String> map) {
        String videoId = map.get("videoId").toString();
        for (int i = 0; i < list.size(); i++) {

            VideoEntity videoListBean = list.get(i);
            if (videoListBean.videoId.equals(videoId)) {
                if (map.containsKey("totalCommentNum")) {

                    videoListBean.videoCommentCounts=map.get("totalCommentNum");
                }
                if (map.containsKey("videoShareCounts")) {
                    videoListBean.videoShareCounts=map.get("videoShareCounts");
                }
                if (map.containsKey("videoLikeCounts")) {
                    videoListBean.videoLikeCounts=map.get("videoLikeCounts");
                }
                if (map.containsKey("isLike")) {
                    videoListBean.isLike=map.get("isLike");
                }
                if (map.containsKey("videoCollectCounts")) {
                    videoListBean.videoCollectCounts=map.get("videoCollectCounts");
                }
                if (map.containsKey("isCollect")) {
                    videoListBean.isCollect=map.get("isCollect");
                }
                adapter.notifyItemChanged(i);
            }
        }
    }
}
